package com.jdkj.tools.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HttpClient工具类
 */
public class HttpClientUtil {

    static final int TIMEOUT_MSEC = 5 * 1000*30;

    /**
     * 发送GET方式请求
     *
     * @param url
     * @param paramMap
     * @return
     */
    public static String doGet(String url, Map<String, String> paramMap, Header[]headers) {
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                SSLContexts.createDefault(),
                new String[]{"TLSv1.2", "TLSv1.3"}, // 允许的协议
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier()
        );

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .build();


        String result = "";
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }
            URI uri = builder.build();

            //创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            //设置请求头
            for (int i = 0; i < headers.length; i++) {
                httpGet.setHeader(headers[i]);
            }

            //发送请求
            response = httpClient.execute(httpGet);

            //判断响应状态
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    /**
     * 发送POST方式请求，form表单
     *
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> paramMap, Header[] headers) throws IOException {
        CloseableHttpClient httpClient = HttpClients.custom()
                .build();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建POST请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 添加多值参数 fieldsToRetain
                String[] retainFields = new String[] {
                        "project", "issuetype", "assignee",
                        "customfield_10401", "customfield_10402",
                        "customfield_10400", "customfield_10404"
                };
                for (String field : retainFields) {
                    paramList.add(new BasicNameValuePair("fieldsToRetain", field));
                }
//                System.out.println(paramList.toString());
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8);
                httpPost.setEntity(entity);
                entity.setContentEncoding("UTF-8");
            }
            for (int i = 0; i < headers.length; i++) {
                httpPost.setHeader(headers[i]);
            }
            httpPost.setConfig(builderRequestConfig());
            // 执行http请求
            response = httpClient.execute(httpPost);
            System.out.println("创建的状态码"+response.getStatusLine().getStatusCode());
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        } finally {
//            try {
//                response.close();
//            } catch (IOException e) {
////                e.printStackTrace();
//            }
        }

        return resultString;
    }

    public static String doPostForm(String url, Map<String, String> paramMap, Header[] headers) throws IOException {
        CloseableHttpClient httpClient = HttpClients.custom()
                .build();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建POST请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }

                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8);
                httpPost.setEntity(entity);
                entity.setContentEncoding("UTF-8");
            }
            for (int i = 0; i < headers.length; i++) {
                httpPost.setHeader(headers[i]);
            }
            httpPost.setConfig(builderRequestConfig());
            // 执行http请求
            response = httpClient.execute(httpPost);
//            System.out.println(response.getStatusLine().getStatusCode());
//            System.out.println("q");
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {

        } finally {
//            try {
//                response.close();
//            } catch (IOException e) {
////                e.printStackTrace();
//            }
        }

        return resultString;
    }
    public static String doPostObject(String url, Map<String, Object> paramMap, Header[] headers) throws IOException {

        CloseableHttpClient httpClient = HttpClients.custom().build();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建POST请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, Object> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), (String) param.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8);
                httpPost.setEntity(entity);
                entity.setContentEncoding("UTF-8");
            }
            for (int i = 0; i < headers.length; i++) {
                httpPost.setHeader(headers[i]);
            }
            httpPost.setConfig(builderRequestConfig());
//            System.out.println(httpPost.getURI());
            // 执行http请求
            response = httpClient.execute(httpPost);
//            Header[] allHeaders = response.getAllHeaders();

//            for (Header allHeader : allHeaders) {
//                if (allHeader.getName().equals("set-cookie")){
//                    System.out.println("cookie"+allHeader.getValue());
//                }
//             }
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 发送POST方式请求，json
     *
     * @param url
     * @param paramMap
     * @return
     * @throws IOException
     */
    public static String doPost(String url, Map<String, Object> paramMap) throws IOException {
        // 创建Httpclient对象
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                SSLContexts.createDefault(),
                new String[]{"TLSv1.2", "TLSv1.3"}, // 允许的协议
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier()
        );

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .build();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (paramMap != null) {
                //构造json格式数据
                JSONObject jsonObject = new JSONObject();
                for (Map.Entry<String, Object> param : paramMap.entrySet()) {
                    jsonObject.put(param.getKey(), param.getValue());
                }
                StringEntity entity = new StringEntity(jsonObject.toString(), "utf-8");
                //设置请求编码
                entity.setContentEncoding("utf-8");
                //设置数据类型
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
                System.out.println("Request URL: " + url);
                System.out.println("Request Method: POST");
                System.out.println("Request Body: " + jsonObject.toString());
            }
            System.out.println(httpPost.getEntity());
            httpPost.setConfig(builderRequestConfig());
            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC).build();
    }

   //移动文件
    public static String doPut(String url, Map<String, Object> paramMap, Header[] headers) throws IOException {
        CloseableHttpClient httpClient = HttpClients.custom().build();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建POST请求
            HttpPut httpPost = new HttpPut(url);
            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, Object> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), (String) param.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8);
                httpPost.setEntity(entity);
                entity.setContentEncoding("UTF-8");
            }
            //设置请求头
            for (int i = 0; i < headers.length; i++) {
                httpPost.setHeader(headers[i]);
            }
            httpPost.setConfig(builderRequestConfig());
            // 执行http请求
            response = httpClient.execute(httpPost);
            System.out.println("put请求"+response.getStatusLine().getStatusCode());
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


    public static String getLoginCookie(String url, Map<String, Object> paramMap, Header[] headers) throws IOException {

        CloseableHttpClient httpClient = HttpClients.custom().build();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建POST请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, Object> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), (String) param.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8);
                httpPost.setEntity(entity);
                entity.setContentEncoding("UTF-8");
            }
            for (int i = 0; i < headers.length; i++) {
                httpPost.setHeader(headers[i]);
            }
            httpPost.setConfig(builderRequestConfig());
//            System.out.println(httpPost.getURI());
            // 执行http请求
            response = httpClient.execute(httpPost);
            Header[] allHeaders = response.getAllHeaders();

            for (Header allHeader : allHeaders) {
//                System.out.println(allHeader.getName()+" "+allHeader.getValue());
                if (allHeader.getName().equals("Set-Cookie")){
                    return allHeader.getValue();
                }
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String LoginDoGet(String url, Map<String, String> paramMap, Header[]headers) {
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                SSLContexts.createDefault(),
                new String[]{"TLSv1.2", "TLSv1.3"}, // 允许的协议
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier()
        );

        CloseableHttpClient httpClient = HttpClients.custom()
                .build();


        String result = "";
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }
            URI uri = builder.build();

            //创建GET请求
            HttpGet httpGet = new HttpGet(uri);

            //设置请求头
            for (int i = 0; i < headers.length; i++) {
                httpGet.setHeader(headers[i]);
            }
            Header[] allHeaders = response.getAllHeaders();
            for (Header allHeader : allHeaders) {
//                System.out.println(allHeader.getName()+" "+allHeader.getValue());
                if (allHeader.getName().equals("Set-Cookie")){
                    return allHeader.getValue();
                }
            }
            //发送请求
            response = httpClient.execute(httpGet);

            //判断响应状态
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }


}
